package data

import (
	"context"
	"platform-sastay-file/internal/biz"
	"platform-sastay-file/internal/conf"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-redis/redis/v8"
)

type domainNameRepo struct {
	log  *log.Helper
	conf *conf.Data
	data *Data
}

func NewDomainNameRepo(logger log.Logger, conf *conf.Data, data *Data) biz.DomainNameRepo {
	return &domainNameRepo{
		log:  log.NewHelper(log.With(logger, "module", "repo/domainName")),
		conf: conf,
		data: data,
	}
}

// PutDomain 更新域名映射
func (d *domainNameRepo) PutDomain(ctx context.Context, ip, domainName string) error {
	return d.data.redis.Set(ctx, ip, domainName, 0).Err()
}

// GetDomain 获取域名信息
func (d *domainNameRepo) GetDomain(ctx context.Context, ip string) (*biz.DomainNameMap, error) {
	domainName, err := d.data.redis.Get(ctx, ip).Result()
	if err == redis.Nil {
		return nil, biz.ErrDomainNameNotFound
	}
	if err != nil {
		return nil, err
	}
	return &biz.DomainNameMap{
		DomainName: domainName,
		IP:         ip,
	}, nil
}
